import json
import os
import time
import requests

os.chdir('D:')
file_name = "login_data.json"
url = 'http://1.1.1.3/ac_portal/login.php'


# RC4加密算法
def rc4(src: str, passwd: str) -> str:
    i, j, a, b, c = 0, 0, 0, 0, 0
    key, sbox = [], []
    plen = len(passwd)
    size = len(src)
    output = ""

    for i in range(256):
        key.append(ord(passwd[i % plen]))
        sbox.append(i)
    for i in range(256):
        j = (j + sbox[i] + key[i]) % 256
        temp = sbox[i]
        sbox[i] = sbox[j]
        sbox[j] = temp
    for i in range(size):
        a = (a + 1) % 256
        b = (b + sbox[a]) % 256
        temp = sbox[a]
        sbox[a] = sbox[b]
        sbox[b] = temp
        c = (sbox[a] + sbox[b]) % 256
        temp = ord(src[i]) ^ sbox[c]
        temp = str(hex(temp))[-2:]
        temp = temp.replace('x', '0')
        output += temp
    return output


if not os.path.exists(file_name):
    account = input("请输入你的账号: ")
    password = input("请输入你的密码: ")
    res = {
        'account': account,
        'password': password
    }
    print(res)
    with open(file_name, "w+") as fp:
        fp.write(json.dumps(res))
else:
    results = os.system('ping www.baidu.com')
    if results != 0:
        with open(file_name, "r") as fp:
            res = json.loads(fp.read())
        account = res['account']
        password = res['password']

        rc4key = int(time.time() * 1000)
        pwd = rc4(password, str(rc4key))

        data = {
            "opr": "pwdLogin",
            "userName": account,
            "pwd": pwd,
            "rc4Key": rc4key,
            "rememberPwd": "0"
        }

        header = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            "Content-Length": "88",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Host": "1.1.1.3",
            "Origin": "http://1.1.1.3",
            "Referer": "http://1.1.1.3/ac_portal/default/pc.html?template=default&tabs=pwd&vlanid=0&url=http://www.msftconnecttest.com%2fredirect",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }

        result = requests.post(url, data, headers=header).status_code
        if result == 200:
            print("用户:" + account + ",登陆成功,状态码为:" + format(result))
        else:
            print("用户:" + account + ",登陆失败,状态码为:" + format(result))
